package com.sky.service.impl;

import com.sky.controller.admin.ReportController;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistic(LocalDate begin, LocalDate end) {
        //1.获取每一天的时间，然后封装到dateList集合中 假如5.2-5.8之间的每一天时间
        //创建一个空的集合，用来承载每一天的日期
        //在原来的日期基础之上加1
        List<LocalDate> datelist = new ArrayList<LocalDate>();
        datelist.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        //2.获取每一天所对应的营业额，然后封装到turnoverList集合中
        //2.1 当天的最小和最大时间
        //2.2 调用mapper接口
        List turnoverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("min", min);
            map.put("max", max);
            Double turnover = orderMapper.sumByMap(map);
            turnoverList.add(turnover == null ? 0 : turnover);
        }
        //3.封装数据，并返回
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return Result.success(vo);
    }

    /**
     * 用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间区间内的每一天的时间
        //1.1 定义一个list用来封装每一天的时间
        List<LocalDate> dateList = new ArrayList<>();
        //1.2插入初始时间
        dateList.add(begin);
        //1.3 插入第一天后的每一天的时间到list集合中
        while (!begin.equals(end)) {//如果当前时间不等于最后一天的话
            begin = begin.plusDays(1);//在指定的时间+1天
            dateList.add(begin);//把每一天的日期加入list集合中
        }
        //1.4 定义两个list用来封装每天的新增用户数量和总用户量
        List<Integer> newUserCountList = new ArrayList<>();
        List<Integer> totalUserCountList = new ArrayList<>();
        //2.查询mysql,查询每一天的新增用户和总用户量
        for (LocalDate date : dateList) {
            //2.1.获取当天的最小时间，年月日时分秒 00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //2.2 获取当天的最大时间，年月日时分秒 59:59
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            //2.3 查询mysql 获取当天的总用户数量 select count(id) from user where  create_time<#{end}
            map.put("end", endTime);
            Integer totalUserCount = userMapper.getUserCount(map);
            //2.4查询mysql获取当天的新增用户数量  select count(id) from user where create_time>#{begin} and create_time<#{end}
            map.put("begin", beginTime);
            Integer newUserCount = userMapper.getUserCount(map);
            //2.5 插入数据到list中
            newUserCountList.add(newUserCount);
            totalUserCountList.add(totalUserCount);
        }
        //3.返回数据
        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserCountList, ","))
                .totalUserList(StringUtils.join(totalUserCountList, ","))
                .build();
        return vo;
    }

    /**
     * 根据时间区间统计订单数量
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间区间内的每一天的时间
        //1.1 定义一个list用来封装每一天的时间
        List<LocalDate> dateList = new ArrayList<>();
        //1.2插入初始时间
        dateList.add(begin);
        //1.3 插入第一天后的每一天的时间到list集合中
        while (!begin.equals(end)) {//如果当前时间不等于最后一天的话
            begin = begin.plusDays(1);//在指定的时间+1天
            dateList.add(begin);//把每一天的日期加入list集合中
        }
        //2.5 定义两个list用来封装每天的总订单数和有效订单数
        List<Integer> totalOrdersCountList = new ArrayList<>();
        List<Integer> validOrdersCountList = new ArrayList<>();
        //2.查询mysql,查询每天的总订单数和有效订单数
        for (LocalDate date : dateList) {
            //2.1.获取当天的最小时间，年月日时分秒 00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //2.2 获取当天的最大时间，年月日时分秒 59:59
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //2.3 查询mysql 获取当天的总订单数  select count(id) from orders where  order_time>#{begin} and order_time<#{end}
            Map map = new HashMap();
            map.put("end", endTime);
            map.put("begin", beginTime);
            Integer totalOrdersCount = orderMapper.getOrderCount(map);
            //2.4查询mysql获取当天的有效订单数量 select count(id) from orders where  order_time>#{begin} and order_time<#{end} and status=5
            map.put("status", Orders.COMPLETED);
            Integer validOrdersCount = orderMapper.getOrderCount(map);
            //2.6 插入数据到list中
            totalOrdersCountList.add(totalOrdersCount);
            validOrdersCountList.add(validOrdersCount);
        }
        //2.7 获取时间区间内的总订单数和有效订单数以及订单完成率
        //聚合求和总订单数
        Integer totalOrdersCount = totalOrdersCountList.stream().reduce(Integer::sum).get();
        //聚合求和有效订单数
        Integer validOrdersCount = validOrdersCountList.stream().reduce(Integer::sum).get();
        //订单完成率=有效订单数/总订单数
        Double orderCompletionRate = 0.0;
        if (totalOrdersCount != 0) {
            orderCompletionRate = validOrdersCount.doubleValue() / totalOrdersCount;
        }
        //3.返回数据
        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalOrdersCountList, ","))
                .validOrderCountList(StringUtils.join(validOrdersCountList, ","))
                .totalOrderCount(totalOrdersCount)
                .validOrderCount(validOrdersCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return vo;
    }

    /**
     * 查询指定时间区间内的销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.转化时间格式
        //1.1.获取当天的最小时间，年月日时分秒 00:00
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        //1.2 获取当天的最大时间，年月日时分秒 59:59
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.根据时间区间查询销量(订单表和订单详情表),包含菜品名称，以及对应的销量数
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getSalesTop10(beginTime, endTime);
        //3.获取商品名称列表
        List<String> nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //4.获取销量列表
        List<Integer> numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //5.返回数据
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return vo;
    }

    /**
     * 报表导出
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
            //2.2 获取近30天的时间
            LocalDate begin = LocalDate.now().minusDays(30); //-30
            LocalDate end = LocalDate.now().minusDays(1);//-1


            //1.获取模板文件
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

            //2.获取excel文件对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //2.1 为第二行的第二个单元格赋值，时间
            sheet.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);

            //2.3 概览数据赋值
            //2.3.1 获取近1个月内的相关数据
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            //2.3.2 excel相关
            XSSFRow row = sheet.getRow(3);
            //营业额单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            //有效订单
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //2.4 明细数据-每一天的
            for (int i = 0; i < 30; i++) {
                //2.4.1 获取每一天的对应的数据
                //获取每一天的时间
                LocalDate date = begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //2.4.2 excel相关操作
                row = sheet.getRow(7 + i);
                //日期
                row.getCell(1).setCellValue(date.toString());
                //营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //写操作
            excel.write(response.getOutputStream());

            //关闭资源
            excel.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}